package com.zqu.ordersystem.controller;

import com.google.gson.Gson;
import com.zqu.ordersystem.entity.Dishes;
import com.zqu.ordersystem.entity.Result;
import com.zqu.ordersystem.service.DishesService;
import com.zqu.ordersystem.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@CrossOrigin
@Slf4j
public class DishesController {

    @Autowired
    private DishesService dishesService;

    @Autowired
    private FileUploadService fileUploadService;


    // 获取所有菜品
    @GetMapping("/dishes")
    public Result getAllDishes() {
        List<Dishes> dishes = dishesService.queryAllDishes();
        return new Result(dishes,"查询成功",200);
    }

    //获取单个菜品
    @GetMapping("/dish/{id}")
    public Result getDishById(@PathVariable Integer id) {
        Dishes dishes = dishesService.queryDishById(id);
        return new Result(dishes,"查询成功",200);
    }

    //按名称模糊查询
    @PostMapping("/dishes/search")
    public Result searchDishesByName(@RequestBody Dishes dishes) {
        log.debug("Searching dishes by name: {}", dishes.getDishesName());
        List<Dishes> dishesList = dishesService.queryDishByName(dishes.getDishesName());
        return new Result(dishesList,"查询成功",200);
    }

    //分页获取
    @GetMapping("/dishes/current/{current}/size/{size}")
    public Result getAllPage(@PathVariable Integer current, @PathVariable Integer size) {
        return new Result(dishesService.queryPage(current, size), "查询成功", 200);
    }

    // 条件分页查询
    @PostMapping("/dishes/current/{current}/size/{size}")
    public Result getConditionPage(@PathVariable Integer current, @PathVariable Integer size, @RequestBody Dishes dishes) {
        log.debug("dishesName is {}", dishes.getDishesName());
        List<Dishes> dishesList = dishesService.queryDishByName(dishes.getDishesName());
        log.debug("dishesList is {}",dishesList);
        return new Result(dishesService.queryConditionPage(dishes, current, size), "查询成功", 200);
    }

    // 删除单个菜品
    @DeleteMapping("/dish/{id}")
    public Result deleteDish(@PathVariable Integer id) {
        Integer del = dishesService.deleteDishById(id);
        if(del == null || del <= 0){
            log.error("删除菜品失败, id: {}", id);
            return new Result(null,"删除菜品失败",401);
        }
        return new Result(null,"删除菜品成功",200);
    }

    // 创建单个菜品（支持图片上传）
    @PostMapping(value = "/dish", consumes = "multipart/form-data")
    public Result createDish(@RequestPart(value = "dishes", required = false) String dishesJson,
                           @RequestParam(value = "image", required = false) MultipartFile image) {
        try {
            // 1. 解析菜品数据
            log.debug("接收到的菜品JSON数据: {}", dishesJson);
            Gson gson = new Gson();
            Dishes dishes = gson.fromJson(dishesJson, Dishes.class);
            log.debug("解析后的菜品对象: {}", dishes);

            // 2. 添加菜品基本信息
            Integer add = dishesService.addDish(dishes);
            log.debug("添加菜品结果: {}, 新菜品ID: {}", add, dishes.getId());
            if(add == null || add <= 0){
                log.error("创建菜品失败, dishes: {}", dishes);
                return new Result(null,"创建菜品失败",401);
            }

            // 2. 处理图片上传
            if (image != null && !image.isEmpty()) {
                log.debug("开始上传菜品图片, 菜品ID: {}", dishes.getId());
                String imageUrl = fileUploadService.uploadDishImage(dishes.getId(), image);
                log.debug("图片上传成功, URL: {}", imageUrl);

                // 3. 更新菜品图片URL
                Dishes existingDish = dishesService.queryDishById(dishes.getId());
                existingDish.setImgUrl(imageUrl);
                Integer update = dishesService.updateDish(existingDish);
                if(update == null || update <= 0){
                    log.error("更新菜品图片URL失败, dishes: {}", existingDish);
                    // 即使图片URL更新失败，也返回成功，但提示图片可能未保存
                    return new Result(dishes,"创建菜品成功，但图片可能未保存",200);
                }
                dishes.setImgUrl(imageUrl);
            }

            return new Result(dishes,"创建菜品成功",200);
        } catch (Exception e) {
            log.error("创建菜品过程中发生异常", e);
            return new Result(null,"创建菜品过程中发生异常: " + e.getMessage(),500);
        }
    }

    // 更新单个菜品（支持图片上传）
    @PutMapping(value = "/dish/{id}", consumes = "multipart/form-data")
    public Result updateDish(@PathVariable Integer id,
                           @RequestPart(value = "dishes", required = false) Dishes dishes,
                           @RequestParam(value = "image", required = false) MultipartFile image) {
        dishes.setId(id);
        if (image != null) {
            String imageUrl = fileUploadService.uploadDishImage(id, image);
            dishes.setImgUrl(imageUrl);
        }
        Integer update = dishesService.updateDish(dishes);
        if(update == null || update <= 0){
            log.error("更新菜品失败, dishes: {}", dishes);
            return new Result(null,"更新菜品失败",401);
        }
        return new Result(dishes,"更新菜品成功",200);
    }

    //按分类查询
    @GetMapping("/dishes/cod/{cod}/index/{index}")
    public Result getDishByCod(@PathVariable Integer cod, @PathVariable Integer index) {
        return new Result(dishesService.queryByCod(cod, index), "查询成功", 200);
    }
}
